import { useUserStore } from '../stores/user';
import { API_BASE_URL, API_TIMEOUT, API_HEADERS, API_STATUS, CRYPTO_KEY } from '../api/config';
import { decryptData } from './crypto';

// 请求配置接口
interface RequestOptions {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  header?: Record<string, string>;
  timeout?: number;
  baseURL?: string;
  [key: string]: any;
}

// 响应接口
interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
}

/**
 * 创建请求对象
 * @param options 请求配置
 * @returns Promise
 */
const request = <T = any>(options: RequestOptions): Promise<ApiResponse<T>> => {
  // 默认配置
  const defaultOptions: RequestOptions = {
    url: '',
    method: 'GET',
    data: {},
    header: API_HEADERS,
    timeout: API_TIMEOUT,
    baseURL: 'https://jsdailyapi.lihk.top/api',
    // baseURL: 'http://192.168.1.244:21904',
  };

  // 合并配置
  const mergedOptions = {
    ...defaultOptions,
    ...options,
  };

  // 获取用户信息
  const userStore = useUserStore();
  if (userStore.token) {
    mergedOptions.header = {
      ...mergedOptions.header,
      Authorization: `Bearer ${userStore.token}`
    };
  }

  // 返回Promise
  return new Promise<ApiResponse<T>>((resolve, reject) => {
    // 构建完整URL - 添加代理逻辑处理跨域
    let fullUrl = mergedOptions.baseURL ? `${mergedOptions.baseURL}${mergedOptions.url}` : mergedOptions.url;

    uni.request({
      ...mergedOptions,
      url: fullUrl,
      success: (res: UniApp.RequestSuccessCallbackResult) => {
        // 请求成功
        let { statusCode, data } = res;

        console.log('CR', CRYPTO_KEY, fullUrl);

        if (CRYPTO_KEY && typeof data === 'object' && 'data' in data && typeof data.data === 'string') {
          // 解密响应数据
          data.data = decryptData(data.data);
        }

        // 处理HTTP状态码
        if (statusCode >= 200 && statusCode < 300) {
          // 处理业务状态码
          if (typeof data === 'object' && 'code' in data && data.code !== API_STATUS.SUCCESS) {
            // 处理特定错误码
            if (data.code === API_STATUS.UNAUTHORIZED) {
              // 未登录或token过期，清除登录状态
              userStore.logout();
              // 不自动跳转，让页面自己处理
            }
            uni.showToast({
              title: data.message || '请求失败',
              icon: 'none'
            });
            reject(new Error(data.message || '请求失败'));
          } else {
            // 确保返回的数据符合ApiResponse接口
            const responseData = data as unknown as ApiResponse<T>;
            resolve(responseData);
          }
        } else {
          // HTTP错误
          handleHttpError(statusCode, reject);
        }
      },
      fail: (err: UniApp.GeneralCallbackResult) => {
        // 请求失败
        uni.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
        reject(new Error(err.errMsg || '网络请求失败'));
      }
    });
  });
};

/**
 * 处理HTTP错误
 * @param statusCode HTTP状态码
 * @param reject Promise拒绝函数
 */
const handleHttpError = (statusCode: number, reject: (reason?: any) => void): void => {
  let message = '请求失败';
  const userStore = useUserStore();

  switch (statusCode) {
    case API_STATUS.UNAUTHORIZED:
      message = '未授权，请登录';
      userStore.logout();
      break;
    case API_STATUS.FORBIDDEN:
      message = '禁止访问';
      userStore.logout();
      break;
    case API_STATUS.NOT_FOUND:
      message = '请求资源不存在';
      break;
    case API_STATUS.SERVER_ERROR:
      message = '服务器错误';
      break;
    default:
      message = `请求失败(${statusCode})`;
  }

  uni.showToast({
    title: message,
    icon: 'none'
  });

  reject(new Error(message));
};

// 封装常用请求方法
const http = {
  /**
   * GET请求
   * @param url 请求地址
   * @param params 请求参数
   * @param options 其他配置
   * @returns Promise
   */
  get: <T = any>(url: string, params: Record<string, any> = {}, options: Partial<RequestOptions> = {}): Promise<ApiResponse<T>> => {
    return request<T>({
      url,
      method: 'GET',
      data: params,
      ...options
    });
  },

  /**
   * POST请求
   * @param url 请求地址
   * @param data 请求数据
   * @param options 其他配置
   * @returns Promise
   */
  post: <T = any>(url: string, data: Record<string, any> = {}, options: Partial<RequestOptions> = {}): Promise<ApiResponse<T>> => {
    return request<T>({
      url,
      method: 'POST',
      data,
      ...options
    });
  },

  /**
   * PUT请求
   * @param url 请求地址
   * @param data 请求数据
   * @param options 其他配置
   * @returns Promise
   */
  put: <T = any>(url: string, data: Record<string, any> = {}, options: Partial<RequestOptions> = {}): Promise<ApiResponse<T>> => {
    return request<T>({
      url,
      method: 'PUT',
      data,
      ...options
    });
  },

  /**
   * DELETE请求
   * @param url 请求地址
   * @param data 请求数据
   * @param options 其他配置
   * @returns Promise
   */
  delete: <T = any>(url: string, data: Record<string, any> = {}, options: Partial<RequestOptions> = {}): Promise<ApiResponse<T>> => {
    return request<T>({
      url,
      method: 'DELETE',
      data,
      ...options
    });
  }
};

export default http;

// 导出响应接口，供其他模块使用
export type { ApiResponse };